package xj.graph2d.command;

import java.awt.geom.Rectangle2D;
import java.util.ListIterator;

import xj.graph2d.DrawShape;
import xj.graph2d.Group;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;

public class AddGroupCommand extends AbstractCommand {

  /*
         * Remove shape, add to group, insert group
         */
  public AddGroupCommand(SimpleDrawView view, SimpleDrawDocument doc,
      Group group, DrawShape parent, DrawShape shape) {
    super(view, doc);
    this.group = group;
    this.parent = parent;
    this.shape = shape;
  }

  public void execute() {
    if (group != null) {
      DrawShape selected = doc.getSelectedShape();
      doc.setSelectedShape(null);
      canvas.repaintShape(selected);
      if (shape != null) {
	if (parent != null) {
	  pos = parent.indexOfShape(shape);
	}
	if (parent == null || pos < 0) {
	  doc.remove(shape);
	  group.addShape(shape);
	  group.doLayout();
	  doc.add(group, true);
	} else {
	  parent.removeShape(pos);
	  group.addShape(shape);
	  group.doLayout();
	  parent.insertShapeAt(group, pos);
	}
      }

      // doc.setSelectedShape(group);
      canvas.repaintShape(group);
    }
  }

  public void undo() {
    if (group != null) {
      Rectangle2D r = group.getBounds();
      if (parent == null) {
	doc.ungroup(group, true);
	doc.remove(group);
      } else {
	parent.removeShape(group);
	ListIterator iter = group.allShapes();
	while (iter.hasNext()) {
	  Object o = iter.next();
	  if (o instanceof DrawShape) {
	    parent.insertShapeAt((DrawShape) o, pos);
	  }
	}
      }
      canvas.repaintRect(r, true);
    }
  }

  protected Group group;

  protected DrawShape shape;

  protected DrawShape parent = null;

  protected int pos = -1;

}
